package com.candy.jdbcutil;

import java.sql.*;

/*
 *  实现JDBC的工具类
 *  定义方法,直接返回数据库的连接对象
 *
 *  写关闭方法
 */

public class JDBCUtil {
   private JDBCUtil(){}
   private static Connection conn;

   static {
       try {
           Class.forName("com.mysql.jdbc.Driver");
           String url="jdbc:mysql://localhost:3306/test1";
           String username = "root";
           String password = "root";
           conn = DriverManager.getConnection(url,username,password);
       } catch (Exception ex) {
           throw new RuntimeException(ex+"数据库连接失败");
       }

   }

   public static Connection getConnection(){
       return conn;
   }

   public static void close(Connection conn, Statement st){
       if(st!=null){
           try {
               st.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
       if(conn!=null){
           try {
               conn.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
   }
   public static void close(Connection conn, Statement st, ResultSet rs){
       if(rs!=null){
           try {
               rs.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
       if(st!=null){
           try {
               st.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
       if(conn!=null){
           try {
               conn.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }

   }
}
